// 用户列表模块
<template>
  <div class="users-container">
    <!-- 面包屑视图 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/#users">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 分配角色弹框 -->

    <el-dialog title="提示" :visible.sync="userSetDialog" width="30%" @close="setDialogClose">
      <div class="title">
        <p>当前用户:
          {{ userInfo.username }}
        </p>
        <p>当前角色:
          {{ userInfo.role_name }}
        </p>
      </div>
      <div class="addNewRole">
        <el-select v-model="newRoleNameId" placeholder="请选择">
          <el-option v-for="item in roleNameList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userSetDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRolesName">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 卡片试图区 -->
    <el-card class="box-card">
      <div class="text item">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="25">
          <el-col :span="7">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4"> <el-button type="primary" @click="centerDialogVisible = true">添加</el-button> </el-col>
        </el-row>
        <!-- 弹框 -->
        <el-dialog title="添加用户" :visible.sync="centerDialogVisible" width="30%" center>
          <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model.trim="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model.trim="addForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model.trim="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model.trim.number="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="adduser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改角色弹框 -->
        <el-dialog title="修改角色" :visible.sync="modUser" width="30%" center>
          <el-form :model="aditFrom" :rules="addFormRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="aditFrom.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="aditFrom.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="aditFrom.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="modUser = false">取 消</el-button>
            <el-button type="primary" @click="editusers">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- table区域 -->
      <el-table :data="userList" border stripe>
        <!-- 索引 -->
        <el-table-column label="#" type="index"></el-table-column>
        <!-- 姓名 -->
        <el-table-column label="姓名" width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ scope.row.username }}</p>
              <p>住址: 江西省抚州市临川区</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.username }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <!-- 邮箱 -->
        <el-table-column label="邮箱" width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <!-- 电话 -->
        <el-table-column label="电话" width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.mobile
            }}</span>
          </template>
        </el-table-column>
        <!-- 角色 -->
        <el-table-column label="角色" width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.role_name
            }}</span>
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">
              <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row.id, scope.row.mg_state)">
              </el-switch></span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="修改该角色资料" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" circle @click="modificationUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="给角色提高权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-help" circle @click="showSetDialog(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除该角色" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" circle @click="deleUser(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 4, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>

export default {
  data() {
    return {
      queryInfo: {
        // 查询参数
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页最多显示多少数据
        pagesize: 4
      },

      userList: null,
      total: 0,
      centerDialogVisible: false, // 弹框
      modUser: false, // 弹框
      userSetDialog: false, // 分配角色弹框
      userInfo: {}, // 需要修改角色的信息
      newRoleNameId: '', // 已选择角色ID
      roleNameList: [], // 角色列表
      aditFrom: { // 编辑的角色信息
      },
      addForm: { // 添加的用户对象
        username: '', // 用户名
        password: '', // 密码
        email: '', // 邮箱
        mobile: '' // 手机号
      },
      addFormRules: { // 规则
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, message: '长度为11位字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取数据
    this.getUserList()
  },
  methods: {
    async getUserList() {
      // 获取数据
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      // 判断数据是否获取成功
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pageSize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改编
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听开关
    async switchChange(id, state) {
      const { data: res } = await this.$http.put(`/users/${id}/state/${state}`)
      // 校验
      if (res.meta.status !== 200) {
        state = !state
        return this.$message.error('修改状态失败')
      } else {
        return this.$message.success('更新状态成功')
      }
    },
    // 添加用户
    async adduser() {
      this.centerDialogVisible = false
      const { data: res } = await this.$http.post('/users', this.addForm)
      if (res.meta.status !== 201) return this.$message.error('添加失败')
      this.getUserList()
      this.$refs.ruleForm.resetFields()
    },
    // 根据 ID 查询角色资料
    async modificationUser(id) {
      const { data: res } = await this.$http.get(`/users/${id}`)
      this.aditFrom = res.data
      this.modUser = true
    },
    //  修改角色
    async editusers() {
      console.log(this.aditFrom.id)
      // 调教 修改 put请求
      const { data: res } = await this.$http.put(`/users/${this.aditFrom.id}`, {
        email: this.aditFrom.email,
        mobile: this.aditFrom.mobile
      })
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.getUserList()
      this.modUser = false
      // 重置表单
      this.$refs.ruleForm.resetFields()
      return this.$message.success('修改成功')
    },
    // 删除角色
    async deleUser(id) {
      const { data: res } = await this.$http.delete(`/users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getUserList()
      return this.$message.success('删除成功')
    },
    // 显示修改角色弹框
    async showSetDialog(iserInfo) {
      // 获取角色列表
      const { data: res } = await this.$http.get('/roles')
      //  校验返回的数据
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.userSetDialog = true
      this.userInfo = iserInfo
      this.roleNameList = res.data
    },
    // 修改角色
    async addRolesName() {
      // 获取用户最新的角色信息
      // 提交修改请求
      const { data: res } = await this.$http.put(`/users/${this.userInfo.id}/role`, { rid: this.newRoleNameId })
      // 对相应回来的数据进行校验
      if (res.meta.status !== 200) return this.$message.error('更新角色失败')
      // 刷新数据
      this.getUserList()
      this.userSetDialog = false
      return this.$message.success('修改角色成功')
    },
    // 监听 修改角色弹窗
    setDialogClose() {
      this.newRoleNameId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style  lang="less" scoped>
.users-container {
  width: 100%;
  height: 100%;

  .el-breadcrumb {
    margin-bottom: 20px;
    font-size: 13px;
  }

  .el-card {
    box-shadow: 0 1px 2px 1px rgba(0, 0, 0, .1);

    .el-table {
      margin-top: 30px;
      font-size: 13px;
    }

    .el-pagination {
      margin-top: 20px;
    }

  }
}
</style>
